using System;
using System.Net;
using System.Net.Sockets;

namespace zTalk.Network
{
    public class ServerEventArgs : EventArgs
    {
        public object Result { get; set; }
        public ServerEventArgs() { }
        public ServerEventArgs(object result) { Result = result; }
    }

    public delegate void ServerEventHandler(object sender, ServerEventArgs ea);

    public class Server
    {
        private Socket socket;
        public int Port { get; set; }

        public static event ServerEventHandler UserQuit;

        public Server()
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        public void Start()
        {
            Console.WriteLine("zTalk Server Started (Ctrl+C to quit)");

            try
            {
                socket.Bind(new IPEndPoint(IPAddress.Any, Port));
                socket.Listen(100);

                while (true)
                {
                    Socket clientScoket = socket.Accept();

                    SocketUser client = new SocketUser();
                    client.Socket = clientScoket;
                    client.Start();

                    Console.WriteLine("Connected {0} ({1} online)", 
                        clientScoket.RemoteEndPoint, SocketWorker.Instances.Count);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        public void Shutdown()
        {
            while (SocketWorker.Instances.Count != 0)
            {
                SocketWorker.Instances[0].Close();
            }
        }

        public static void OnUserQuit(SocketUser user)
        {
            if (UserQuit != null)
            {
                UserQuit(null, new ServerEventArgs(user));
            }
        }
    }
}
